package com.aixin.project.servlet.admin;

import com.aixin.project.data.Expert;
import com.aixin.project.data.User;
import com.aixin.project.handler.ExpertHandler;
import com.aixin.project.handler.UserHandler;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Sufeng
 * Date: 12-5-18
 * Time: 上午5:36
 * To change this template use File | Settings | File Templates.
 */
public class OnlineServlet extends AdminServlet{
    @Override
    protected Template execute(HttpServletRequest request, HttpServletResponse response, Context ctx) {
        ServletContext application  = getServletContext();

        HashMap<Long, Integer> registerUser = (HashMap<Long, Integer>) application.getAttribute("registerUser");
        HashMap<Long, Integer> registerExpert = (HashMap<Long, Integer>) application.getAttribute("registerExpert");
        Integer anonyUserCount = (Integer) application.getAttribute("anonyUserCount");

        Integer totalOnline = 0;
        List<User> onlineUser = new ArrayList<User>();
        List<Expert> onlineExpert = new ArrayList<Expert>();

        Iterator<Long> itu =  registerUser.keySet().iterator();
        while(itu.hasNext()){
            Long uid = itu.next();
            Integer unum = registerUser.get(uid);
            unum = (unum==null?0:unum);
            totalOnline += unum;
            User user = UserHandler.find(uid);
            if(user!=null){
                System.out.println("online user:"+user.getUsername());
                user.setOnline(unum);
                onlineUser.add(user);
            }
        }

        Iterator<Long> ite =  registerExpert.keySet().iterator();
        while(ite.hasNext()){
            Long eid = ite.next();
            int e_num = registerExpert.get(eid);
            totalOnline += e_num;
            Expert expert = ExpertHandler.find(eid);
            if(expert!=null){
                expert.setOnline(e_num);
                onlineExpert.add(expert);
            }
        }
        totalOnline += anonyUserCount;

        ctx.put("totalOnline",totalOnline);
        ctx.put("anonyUserCount",anonyUserCount);
        ctx.put("onlineUser",onlineUser);
        ctx.put("onlineExpert",onlineExpert);
        return getTemplate("bg/online.vm");  //To change body of implemented methods use File | Settings | File Templates.
    }
}
